function lineFound()
  return activeLightReading(3) < 37
end

function resetAndFlip(motor)
  speed = speedReading(motor)
  resetRotationCount(motor)
  forward(motor, -speed)
end

function flipAndSearch(distance, finder)
  resetAndFlip(A)
  forward(B, -speedReading(A))
  repeat until finder() or abs(rotationCounts(A)) > distance
end

function search(finder) 
  distance = 10
  repeat
    flipAndSearch(distance)
    distance = distance * 2
  until finder()
end

repeat
  light = activeLightReading(3)
  if not lineFound() then
    forward(A)
    forward(B)
  else 
    search(lineFound)
  end
until isPressed(ESCAPE)



